//
//  MapLocationViewController.m
//  HaoHaiSpell
//
//  Created by haohai on 16/6/23.
//  Copyright © 2016年 海城. All rights reserved.
//

#import "MapLocationViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <MAMapKit/MAMapKit.h>
#import "ProvinceModel.h"
#import "RegionModel.h"
#import "MapCell.h"

#define kUrl @"http://wfx.hostadmin.com.cn/app/app.php?op=getcityid&verify=e10adc3949ba59abbe56e057f20f883"

@interface MapLocationViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic,strong)UICollectionView *city_pickView;
@property (nonatomic,strong)NSMutableArray *cityArray;
@property (nonatomic,strong)NSMutableArray *regionArray;
@property (nonatomic,strong)NSString *cityName;
@property (nonatomic,strong)NSString *regionName;
@property (nonatomic,strong)NSMutableArray *allDataSource;
@property (nonatomic,strong)NSMutableDictionary *parameter;
@end

@implementation MapLocationViewController
#pragma mark - 懒加载
-(UICollectionView *)city_pickView{

    if (!_city_pickView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
     
        _city_pickView =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, kWidth - 40, kHeight - 164) collectionViewLayout:layout];
        _city_pickView.dataSource = self;
        _city_pickView.delegate = self;
        _city_pickView.backgroundColor = [UIColor whiteColor];
    }
    return _city_pickView;
}

-(NSMutableArray *)cityArray{

    if (!_cityArray) {
        _cityArray = [NSMutableArray new];
    }
    return _cityArray;
}

-(NSMutableArray *)regionArray{

    if (!_regionArray) {
        _regionArray = [NSMutableArray new];
    }
    return _regionArray;
}


-(NSMutableArray *)allDataSource{

    if (!_allDataSource) {
        _allDataSource = [NSMutableArray new];
    }
    return _allDataSource;
}

-(NSMutableDictionary *)parameter{

    if (!_parameter) {
        _parameter = [NSMutableDictionary dictionaryWithDictionary:@{@"op":@"city",@"verify":@"e10adc3949ba59abbe56e057f20f883e"}];
    }
    return _parameter;
}

#pragma mark - 数据请求
-(void)fetchDataWithUrl:(NSString *)url parameter:(NSDictionary *)parameter{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSArray *contentArray = dic[@"content"];
        for (NSDictionary *mDic in contentArray) {
            ProvinceModel *model = [[ProvinceModel alloc]init];
            [model setValuesForKeysWithDictionary:mDic];
            [self.cityArray addObject:model];
           }
        [self.city_pickView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"数据请求失败");
    }];
}


-(void)createView{

    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, kWidth / 3, 20)];
    titleLabel.text = @"请选择区域";
    [self.view addSubview:titleLabel];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setFrame:CGRectMake(kWidth - 80,10, 45, 20)];
    [backBtn addTarget:self action:@selector(backPreView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}

-(void)backPreView:(UIButton *)sender{


    [self.view removeFromSuperview];
}


-(void)queryData{

//    NSString *url = @"http://wfx.hostadmin.com.cn/app/app.php";
//    [self fetchDataWithUrl:url parameter:self.parameter];
//    for (ProvinceModel *model in self.cityArray) {
//        NSArray *disArr = model.dis;
//        for (NSDictionary *mDic in disArr) {
//            RegionModel *model = [[RegionModel alloc]init];
//            [model setValuesForKeysWithDictionary:mDic];
//        }
//    }
//    NSLog(@"city:%@      region:%@",self.cityArray,self.regionArray);
    NSString *path = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
    NSArray *provincesArray = [[NSArray alloc]initWithContentsOfFile:path];
    [provincesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.cityArray addObject:obj[@"state"]];
    }];
    
    NSMutableArray *city = [NSMutableArray arrayWithArray:[provincesArray firstObject][@"cities"]];
    [city enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.regionArray addObject:obj[@"city" ]];
    }];
}

#pragma mark - 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = HWColor(245, 245, 245);
    [self.city_pickView registerNib:[UINib nibWithNibName:@"MapCell" bundle:nil] forCellWithReuseIdentifier:@"mapCell"];
    [self.view addSubview:self.city_pickView];
    [self createView];
    // 请求数据
    [self queryData];
    
    
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{


    return self.regionArray.count;
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{


    return self.cityArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MapCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"mapCell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor yellowColor];
    if (indexPath.row == 0) {
        
        cell.titleLabel.text = self.cityArray[indexPath.section];
    }else{
        cell.titleLabel.text = self.regionArray[indexPath.row];
    }
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(10, 10, 10, 10);
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return CGSizeMake(80, 150);
    }
    return CGSizeMake(35, 20);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        self.cityName = self.cityArray[indexPath.section];
    }else{
        self.cityName = self.regionArray[indexPath.row];
    }
    [Site_ID sharedSite_ID].cityName = self.cityName;
    
    NSLog(@"cityName = %@",[Site_ID sharedSite_ID].site_id);
}




@end
